<?php

namespace globalunit\utils;

/**
 * PHP实现RSA分段加密、解密
 *
 * Class RSA
 */

if (!function_exists('url_safe_base64_decode')) {
    function url_safe_base64_decode($data)
    {
        $base_64 = str_replace(array(" ",'-','_'), array("+",'+','/'), $data);
        return base64_decode($base_64);
    }
}

class RsaUtil
{
    public $privateKey = './rsa_private_key.pem';           //私钥地址
    public $publicKey = './rsa_public_key.pem';             //公钥地址

    public $pri_key = '-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAO/c4xhnz+HCQlq0
C0iLumxoTnUqTerWYz0lj4//6m/x5YgoOaZP07uhe+pNHpN5adVlHGbjEt2y3wu0
iH9TdCOoBO8Id1HK9HwSJsMmTJObqGTArXpVDOgioSqBUoEtFaqKBfG8n9iOEADc
a/X0frc26PfzKaDhFGkdEyTzFpPpAgMBAAECgYAJ0sYKLdY5rLcC9/SuV+qenfb4
nW7rezQ9QNiMUTLMut9noB4cTZCiUo68ncPuzj4jWyy6mfof0j+IPzCH5mcPKnlO
XAQ84qKqHdAqmY4MYKvCrLgOrUuDVqXOXUuzGNHYNPbB7wcr3bXvre3fbk5wmBXX
fPaRJVpFm36JmJmOsQJBAPzTCR21Rli+EIac9Ukgn4EpSWgDedE1IW1faDRwUPpL
Hz/3GN7T3nVQY2vTs8rZLQOBNs06QeaFKLvu1eAVOB8CQQDy4CxfQWLr9d8ZoKft
5ZHLII1gCK028s3ANjeDPnqLmHeQW0GdNuh2bjf34ugbWhqOWzR7MxSXCdGR9mwm
7NL3AkEA0MDruQTxpdqhyJSXD5+JNFvDycd88RoelLF/WDUZF+GpVuaPOYXVHCaZ
QPIXdTlnKoqplkExIsb2QF7PZ+v9XwJAQLd5O1yZ9lQKwbJsbNiqM50V7swBE845
AwmvWxpv3viei2m1nyW9ZalS4ouk23zz7JDi+B0RVHm6TRGDmg+q2wJBAI3F9hCl
GpymaFYUTVsUXAA8G/C2RKa1PGSDriu0e0iEzCKLlm9k8l8vYhsEUmHKZ2CaQsB/
HfmBAeARVvE8GVU=
-----END PRIVATE KEY-----';
    public $pub_key = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDv3OMYZ8/hwkJatAtIi7psaE51
Kk3q1mM9JY+P/+pv8eWIKDmmT9O7oXvqTR6TeWnVZRxm4xLdst8LtIh/U3QjqATv
CHdRyvR8EibDJkyTm6hkwK16VQzoIqEqgVKBLRWqigXxvJ/YjhAA3Gv19H63Nuj3
8ymg4RRpHRMk8xaT6QIDAQAB
-----END PUBLIC KEY-----';


    /**
     * RSA constructor.
     * @param null $publicKeyPath
     * @param null $privateKeyPath
     * @param null $publicKey
     * @param null $privateKey
     * @throws FileNotFoundException
     */
    public function __construct($publicKeyPath = "", $privateKeyPath = "", $publicKey = "", $privateKey = "")
    {

        // if ($this->checkKeyFile($publicKeyPath)) {
        //     $this->pub_key = openssl_pkey_get_public(file_get_contents($publicKeyPath));
        // }

        // if ($this->checkKeyFile($privateKeyPath)) {
        //     $this->pri_key = openssl_pkey_get_private(file_get_contents($privateKeyPath));
        // }

        // if (!is_null($publicKey)) {
        //     $this->pub_key = openssl_pkey_get_public($this->formatterPublicKey($publicKey));
        // }

        // if (!is_null($privateKey)) {
        //     $this->pri_key = openssl_pkey_get_private($this->formatterPrivateKey($privateKey));
        // }

    }

    /**
     * 校验文件是否存在
     * @param $keyPath string 文件路径
     * @return bool
     * @throws FileNotFoundException
     */
    public function checkKeyFile($keyPath)
    {
        if (!is_null($keyPath)) {
            if (!file_exists($keyPath)) {
            }

            return true;
        }

        return false;
    }

    /**
     * 格式化公钥
     * @param $publicKey string 公钥
     * @return string
     */
    public function formatterPublicKey($publicKey)
    {
        if (str_contains('-----BEGIN PUBLIC KEY-----', $publicKey)) return $publicKey;

        $str = chunk_split($publicKey, 64, PHP_EOL); //在每一个64字符后加一个\n
        $publicKey = "-----BEGIN PUBLIC KEY-----" . PHP_EOL . $str . "-----END PUBLIC KEY-----";

        return $publicKey;
    }

    /**
     * 格式化私钥
     * @param $privateKey string 公钥
     * @return string
     */
    public function formatterPrivateKey($privateKey)
    {
        if (str_contains('-----BEGIN RSA PRIVATE KEY-----', $privateKey)) return $privateKey;

        $str = chunk_split($privateKey, 64, PHP_EOL); //在每一个64字符后加一个\n
        $privateKey = "-----BEGIN RSA PRIVATE KEY-----" . PHP_EOL . $str . "-----END RSA PRIVATE KEY-----";

        return $privateKey;
    }

    /**
     *  公钥加密（分段加密）
     *  emptyStr    需要加密字符串
     */
    public function encrypt($str)
    {
        $crypted = array();
        $data = $str;
        $dataArray = str_split($data, 117);
        foreach ($dataArray as $subData) {
            $subCrypted = null;
            openssl_public_encrypt($subData, $subCrypted, $this->pub_key);
            $crypted[] = $subCrypted;
        }
        $crypted = implode('', $crypted);
        return base64_encode($crypted);
    }

    /**
     *  私钥解密（分段解密）
     *  @encrypstr  加密字符串
     */
    public function decrypt($encryptstr)
    {

        // $key_eol = (string) implode("\n", str_split((string) $this->key, 64));
        // $priKey = (string) "-----BEGIN PRIVATE KEY-----\n" . $key_eol . "\n-----END PRIVATE KEY-----";

        $encryptstr = url_safe_base64_decode($encryptstr);
        // $encryptstr = base64_decode($encryptstr);
        $decrypted = array();
        $pub_id = openssl_get_publickey($this->pub_key);
        $key_len = openssl_pkey_get_details($pub_id)['bits'];
        $part_len = $key_len / 8;
        var_dump(['part_len' => $part_len]);
        $dataArray = str_split($encryptstr, $part_len);
        foreach ($dataArray as $subData) {
            $subDecrypted = "";
            $res = openssl_private_decrypt($subData, $subDecrypted, $this->pri_key);
            var_dump(['res' => $res, "err" => openssl_error_string()]);
            var_dump(['subDecrypted' => $subDecrypted]);
            $decrypted[] = $subDecrypted;
        }
        $decrypted = implode('', $decrypted);
        return $decrypted;
    }
}



$result = new RsaUtil();

// $data = '{"phone":"15256416396","name":"张三","inAcctNo":"8239472342342342","idNo":"342422165897654326","inAcctBankName":"平安银行"}';

// $dataEn = $result->encrypt($result->pri_key);
// echo $dataEn;
$dataEn = "k2qOgmjfmHR6D8Mfp8YSLB4lEyxYQ_4m-arA1TleraEmvp1QnvIXmOzYFoUopS0Dy5G-Cay6sIX348hmO3MHDL1u5mvDbDKgMZ8Yz0bYKhisRmyBT1Rww6RL0q4HQyRmf_QYe2PNuI8STZrwpm14imO_Ip9MZmRiPt4bIZQjtTbcj5lZxjuTZ5IYMLJn_7n651g1jq746BVvoSFtVb86Bteag-dQnbpur74f_ezGS61HlGpRXGDgNPxFYXu6qS0URodHtJeYKbVEOzU0g-TOoRQiBS5ShpL0Zu2Db7vY4xJQYWRvlyy47wJgKDyN-VLp8WhT1LA23dkXJf21W7zlPAMDTngSVoZheffdyTkWtjzO5rgV6ob1LLT8hrXw_RtuuXzggcD29DgfTS8RSZxe56YC3LtPpxAQFAUTO3ufKrjss08k7a62sZipsScP1qlQMS64gyQ3Tic1tj7QWy-8oq4ohugENN0saDrmETzsQ5APW5hvWXhpPzz-DYVAsUxG0ZJmSA7qM7Q5E9P2bilfuo421qlbcMGpB44aVua7t5xD1vdLwFzvZuWRb5esVsup8z_kz-VqMixQYdcYdZfPD4oIz40pemCwwA4mGkNFkIj5ikTk0nu6HZuERMJSOLS3B29Vtw8Dok-msIysrGZFhcI2FVKVYxrOhNYuziBsSFA=";
// echo "\n";
$dataDe = $result->decrypt($dataEn);
var_dump(["dataDe"=>$dataDe]);
var_dump(["base64_encode"=>base64_decode($dataDe)]);